package server.java.autoduel.Cars;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import server.java.autoduel.Util.XmlFileFilter;

import com.thoughtworks.xstream.XStream;

/**
 * Provides a set of car blueprints for the game to work with
 * 
 * @author Ian Axelrod
 * @author Liz Ha
 * @author Andrew Muldowney
 * @author Edward Futch
 */
public class CarFactory {

	/**
	 * The data directory car xml files are present in
	 */
	private final static String data_dir = "/data/cars/";

	/**
	 * A hash map of all the cars, keyed by their name
	 */
	private static Map<String, Car> cars;

	/**
	 * Loads up all the car data from the server filesystem
	 * 
	 * @throws IOException
	 */
	public static void loadCars(String currentDir) throws IOException {
		final File dir = new File(currentDir + CarFactory.data_dir);
		final File[] files = dir.listFiles(new XmlFileFilter());
		CarFactory.cars = new HashMap<String, Car>();

		for (final File file : files) {
			final FileInputStream reader = new FileInputStream(file);
			final byte[] buf = new byte[(int) file.length()];
			reader.read(buf);
			reader.close();
			final XStream xstream = new XStream();
			xstream.alias("Car", Car.class);
			final Car car = (Car) xstream.fromXML(new String(buf));
			CarFactory.cars.put(car.getName(), car);
		}
	}

	/**
	 * Provides the requested car to the caller
	 * 
	 * @param name
	 *            the name of the car to create
	 * @return a copy of the requested car
	 */
	public static Car provideCar(String name) {
		return CarFactory.cars.get(name).copy();
	}

	/**
	 * Provides to the caller a copy of the internal list of cars available
	 * 
	 * @return the cars available in this factory
	 */
	public static ArrayList<Car> provideCars() {
		final ArrayList<Car> carsCopy = new ArrayList<Car>();

		for (final Car car : CarFactory.cars.values()) {
			carsCopy.add(car.copy());
		}
		return carsCopy;
	}
}